package com.lihua.common.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.DecimalFormat;
import java.time.DayOfWeek;
import java.time.LocalDateTime;

/**
 * @author lihua
 * @date 2022/4/15 17:26
 * 系统计数工具类
 */
@Component
public class SystemCountUtils {

    @Autowired
    private RedisUtils redisUtils;

    /**
     *
     * 用户 type=user-count 新增：key = user-count:星期几 。总数：key = user-count:total
     *
     * 任务 type=task-count
     * @param type 需要计数的类型 用户 type=user-count
     * */
    public void addQuantity(String type){
        //今日新增
        //获取今天是星期几
        DayOfWeek dayOfWeek = LocalDateTime.now().getDayOfWeek();
        int value = dayOfWeek.getValue();
        String key = type+":"+value;
        Integer num = (Integer)redisUtils.get(key);
        if (num==null){
            //两天过期
            redisUtils.set(key,1,86400*3);
        }else {
            //数量加一
            redisUtils.set(key,1+num,86400);
        }

        //总数新增
        String totalKey = type+":"+"total";
        Integer totalNum = (Integer)redisUtils.get(totalKey);
        if (totalNum==null){
            redisUtils.set(totalKey,1);
        }else {
            //数量加一
            redisUtils.set(totalKey,1+totalNum);
        }

    }


    /**
     * 获取总数
     * */
    public int getTotal(String type){
        String totalKey = type+":"+"total";
        Integer totalNum = (Integer)redisUtils.get(totalKey);
        if (totalNum==null){
            return 10;
        }else {
            return  totalNum;
        }

    }

    /**
     * 获取今日新增
     * */
    public int getTodayNum(String type){
        DayOfWeek dayOfWeek = LocalDateTime.now().getDayOfWeek();
        int value = dayOfWeek.getValue();
        String key = type+":"+value;
        Integer userTodayNum =(Integer)redisUtils.get(key);
        if (userTodayNum==null){
            return  0;
        } else {
            return userTodayNum;
        }
    }

    /**
     * 获取比昨日增加比例
     * */
    public String getCompareYesterday(String type){
        DayOfWeek dayOfWeek = LocalDateTime.now().getDayOfWeek();
        int value = dayOfWeek.getValue();
        int yesterday = value-1;
        if (value==1){
            yesterday = 7;
        }
        String yesterdayKey = type+":"+yesterday;
        Integer yesterdayNum = (Integer)redisUtils.get(yesterdayKey);
        int todayNum = getTodayNum(type);
        if (yesterdayNum==null){
            if (todayNum>0){
                return "+100%";
            }
            return "——";
        }
        int addNum = todayNum - yesterdayNum;
        double proportion =addNum/yesterdayNum.doubleValue();
        DecimalFormat df = new DecimalFormat("0.00%");
        return df.format(proportion);
    }

    public static void main(String[] args) {
        int j = 100000;
        String s = String.format("%,d", j);
        System.out.println(s);



    }

}
